
define([], function () {
  'use strict'
  // to-> form
  function merge(form, ...to) {
    form = JSON.parse(JSON.stringify(form))
    const data = Object.assign({}, ...to)
    Object.keys(form).forEach((key) => {
      if (key in data) {
        form[key] = data[key]
      }
    })
    return form
  }
  function tryNumber(val, num = 0) {
    if (Number.isNaN(Number(val))) {
      return num
    }
    return Number(val)
  }
  function isInt(num) {
    const val = Number.parseInt(num)
    if (Number.isNaN(val)) return false
    return val === Number(num)
  }
  function sectionNumber(num, min, max) {
    num = Number(num)
    return num >= min && num <= max
  }
  function isExist(val) {
    if (val === 0) return true
    return !!val
  }
  function awaitTime(time = 2000) {
    let r
    const p = new Promise((resolve) => (r = resolve))
    setTimeout(() => {
      r()
    }, time)
    return p
  }
  // 去重
  function unique(arr, key) {
    return arr.reduce((target, item) => {
      if (target.some((a) => a[key] === item[key])) {
        return target
      }
      target.push(item)
      return target
    }, [])
  }

  function pick(obj, keys) {
    return keys
      .map((k) => (k in obj ? { [k]: obj[k] } : {}))
      .reduce((res, o) => Object.assign(res, o), {})
  }

  function reject(obj, keys) {
    return Object.keys(obj)
      .filter((k) => !keys.includes(k))
      .map((k) => ({ [k]: obj[k] }))
      .reduce((res, o) => Object.assign(res, o), {})
  }
  function initFormReq(from, arr = [], blurArr = []) {
    // form对象所有属性  arr 不需要验证  blurArr 只验证blur
    const rulesObj = JSON.parse(JSON.stringify(from))
    var noArr = arr
    Object.keys(rulesObj).forEach((key) => {
      rulesObj[key] = noArr.includes(key)
        ? ''
          ? (rulesObj[key] = blurArr.includes(key))
          : [
            {
              required: true,
              message: '必填项内容不能为空!',
              trigger: ['blur'],
            },
          ]
        : [
          {
            required: true,
            message: '必填项内容不能为空!',
            trigger: ['blur', 'change'],
          },
        ]
    })
    return rulesObj
  }

  // 判断数据类型
  const objType = (s) => ({}.toString.call(s).split(' ')[1].split(']')[0])

  // 获取随机数
  const random = () => Math.random().toString(36).slice(2)

  // 数组去重
  const uniqBy = (arr = [], key) => [
    ...new Map(arr.map((item) => [item[key], item])).values(),
  ]

  // 数组转对象
  const arrToObjByKey = (arr = [], key) =>
    arr.reduce(
      (obj, item) => ({
        [item[key]]: obj[item[key]] ? obj[item[key]].push(item) : [item],
        ...obj,
      }),
      {}
    )

  // 数组转对象
  const arrToObj = (arr, fn) =>
    arr.reduce((obj, key) => ({ ...obj, [key]: fn?.(key) || '' }), {})

  // 判断数据是否为空
  const isNull = (obj) => {
    return ['', null, undefined].includes(obj)
  }
  // 获取多少天的日期    num Number 
  const getDate = (num) => {
    var date1 = new Date();
    var date2 = new Date(date1);
    date2.setDate(date1.getDate() + num);
    var time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
    return time2;
  }

  //节流
  const throttle = function (fn, delay = 500) {
    let timer = 0;
    return function () {
      if (timer) return
      timer = setTimeout(() => {
        fn.apply(this, arguments)  //透传this和参数
        timer = 0
      }, delay)
    }
  }

  // 当前登录用户角色
  const currentUserRole = function () {
    return $.el.auth.roles.some(c => c.displayEn === 'ADMIN')
  }

  // 删除流程草稿
  const delProcessDraft = function () {
    if ($.form.getMenuInfo().l2Code === 'workbench:process' && window.CACHE_?.processDraft?.id) {
      $.el.del({
        url: ELMP.delUrl('/workflow/v1/proccessDraft/?ids=' + window.CACHE_.processDraft.id),
        success: (r) => {
          return true
        },
        console: (e) => {
          return false
        }
      })
    }

  }
  // 校验表格
  function validateTable(data, columns, preMsg = '') {
    function defaultValidate({ row, column }) {
      const cellValue = row[column.field]
      return isExist(cellValue)
    }
    for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
      const row = data[rowIndex]
      for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {
        const column = columns[columnIndex]
        if (column.children) {
          if (!validateTable(data, column.children)) {
            return false
          }
        }
        if (!column.field) continue
        if (!column.required && !column.validate) continue
        const validateFn = column.validate ?? defaultValidate
        const validate = validateFn({ row, rowIndex, column, columnIndex })
        if (typeof validate === 'object') {
          if (!validate.validate) {
            return false
          }
        }
        if (validate === false) {
          $.msg.tips(`${preMsg}请填写第【${rowIndex + 1}】行-${column.title}`)
          return false
        }
      }
    }
    return true
  }
  return {
    merge,
    tryNumber,
    isInt,
    sectionNumber,
    isExist,
    awaitTime,
    unique,
    initFormReq,
    objType,
    random,
    uniqBy,
    arrToObjByKey,
    arrToObj,
    isNull,
    pick,
    reject,
    getDate,
    throttle,
    // 获取空行数据
    getEmptyRow(columns = []) {
      const row = columns.reduce((result, column) => {
        let defaultValue = ''
        if (isExist(column.defaultValue)) {
          if (typeof column.defaultValue === 'function') {
            defaultValue = column.defaultValue()
          } else {
            defaultValue = column.defaultValue
          }
        }
        if (column.field) {
          result[column.field] = defaultValue
        }
        return result
      }, {})
      return row
    },
    currentUserRole,
    delProcessDraft,
    validateTable
  }
})
